package com.xiaochong.tir.order.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.hbasepo.*;
import com.xiaochong.tir.common.data.redisPo.KActionTotalPo;
import com.xiaochong.tir.common.exception.ErrorDataException;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import com.xiaochong.tir.order.component.hbase.CurrencyInfoHbaseComponent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by admin on 2018/6/11.
 */
@Component
public class OrderDataSaveHbaseCommon {
    @Autowired
    private RedisServer rediscConfig ;
    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;
    @Autowired
    private CurrencyInfoHbaseComponent currencyInfoHbaseComponent;


    /**
     * 买卖单公共消费方法
     * @param body
     */
    public void MqDataSaveOrderBook(byte[] body) {
        try {
            LogTrace.beginTrace("kline-买卖单消费开始");
            if(body == null){
                LogTrace.info("kline-买卖单消费","body","传入内容为空");
                return;
            }
            String params =new String(body, "UTF-8");
            if(StringUtils.isBlank(params)) return;
            OrderBook orderBook = JSON.parseObject(params,OrderBook.class);
            //如果没有数据返回
            LogTrace.info("kline-买卖单消费","明细",orderBook.getExchangeId()+"-"+orderBook.getExchange()+"-"+orderBook.getSymbol());
            if(orderBook == null || orderBook.getExchange() == null || orderBook.getSymbol() == null
                    || orderBook.getData() == null  || orderBook.getExchangeId() == null){
                LogTrace.error("kline-买卖单消费",new ErrorDataException(orderBook.getExchange()+"-"+orderBook.getSymbol()+"无数据"));
                return;
            }
            /*if(orderBook.getExchange().equals("gateio")){
                LogTrace.info("ceshi","c","3");
            }*/
            //获取时间戳转成rowKey，规则：+交易所id+@交易对+@201805020225（年月日时分），买卖单数据保存没意义所以只保存最新一条即可
            //LocalDateTime time = DateUtils.getDateTimeOfTimestamp(orderBook.getTimestamp());
            //得到rowKey
            //String rowKey = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdhm);
            //|| orderBook.getData().getBids() == null || orderBook.getData().getAsks() == null
            if(orderBook.getData().getBids() == null && orderBook.getData().getAsks() == null){
                LogTrace.error("kline-买卖单消费2",new ErrorDataException(orderBook.getExchange()+"-"+orderBook.getSymbol()+"无数据"));
                return;
            }
            String redisKey = RedisKeysUtils.API_SERVICE_ORDER_BOOK+"@"+orderBook.getExchangeId()+"@"+orderBook.getSymbol();
            String redisData = rediscConfig.get(redisKey);
            OrderBook orderBookOld;
            if(StringUtils.isNotBlank(redisData)){
                orderBookOld = JSON.parseObject(redisData,OrderBook.class);
            }else{
                orderBookOld = new OrderBook();
            }
            List<List<Object>> kong = new ArrayList<>();
            if(orderBookOld.getData() == null){
                OrderBookData data = new OrderBookData();
                data.setAsks(kong);
                data.setBids(kong);
                orderBookOld.setData(data);
            }
            orderBookOld.setExchange(orderBook.getExchange());
            orderBookOld.setExchangeId(orderBook.getExchangeId());
            orderBookOld.setSymbol(orderBook.getSymbol());
            //获取redis保存的数据，买单和卖单分别保存100条数据
            if(orderBook.getData().getBids() != null && orderBook.getData().getBids().size() > 0){
                if(orderBookOld.getData().getBids() == null){
                    orderBookOld.getData().setBids(kong);
                }
                orderBookOld.getData().getBids().addAll(orderBook.getData().getBids());
                int cha = orderBookOld.getData().getBids().size() -100;
                if(cha > 0){
                    for(int i=0;i<cha;i++){
                        orderBookOld.getData().getBids().remove(0);
                    }
                }
            }
            if(orderBook.getData().getAsks() != null && orderBook.getData().getAsks().size() > 0){
                if(orderBookOld.getData().getAsks() == null){
                    orderBookOld.getData().setAsks(kong);
                }
                orderBookOld.getData().getAsks().addAll(orderBook.getData().getAsks());
                int cha = orderBookOld.getData().getAsks().size() -100;
                if(cha > 0){
                    for(int i=0;i<cha;i++){
                        orderBookOld.getData().getAsks().remove(0);
                    }
                }
            }
            //因为只保存一条，所以rowkey固定
            String rowKey = HbaseTableUtils.API_SERVICE_ORDER_BOOK_ROWKEY+"@"+orderBook.getExchangeId()+"@"+orderBook.getSymbol();
            LogTrace.info("kline-买卖单","rowKey",rowKey);
            /*String hbaseData = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.API_SERVICE_ORDER_BOOK_TABLE_NAME
                    , HbaseTableUtils.API_SERVICE_ORDER_BOOK_TABLE_NAME_FAMILY
                    , HbaseTableUtils.API_SERVICE_ORDER_BOOK_QUALIFIER
                    , rowKey);*/

            //保存hbase
            currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.API_SERVICE_ORDER_BOOK_TABLE_NAME
                    ,rowKey
                    , HbaseTableUtils.API_SERVICE_ORDER_BOOK_TABLE_NAME_FAMILY
                    , HbaseTableUtils.API_SERVICE_ORDER_BOOK_QUALIFIER
                    ,JSON.toJSONString(orderBookOld));
            LogTrace.info("kline-买卖单","hbase保存","成功");
            //保存数据到redis
            rediscConfig.set(redisKey,JSON.toJSONString(orderBookOld));
            LogTrace.info("kline-买卖单","redis保存","成功");
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("kline-买卖单",e);
        }
    }
}
